package cn.flying.cloud.base.mybatis.configuration;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;

import com.baomidou.mybatisplus.core.incrementer.DefaultIdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;

import cn.flying.cloud.base.mybatis.interceptor.PrintSqlInterceptor;

/**
 * mybatis-plus配置
 *
 * @author: admin
 * @date: 2023年08月29日 20:57
 * @version: 1.0
 */
@PropertySource(value = {"classpath:application.properties", "classpath:config/application.properties"}, ignoreResourceNotFound = true)
@MapperScan("cn.flying.**.mapper")
@Configuration
public class MybatisPlusConfiguration {

    @Value("${mybatis-plus.global.worker-id:${random.int[1,31]}}")
    private Long workerId;

    @Value("${mybatis-plus.global.datacenter-id:${random.int[1,31]}}")
    private Long datacenterId;

    /**
     * 配置分页插件
     *
     * @return
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor mybatisPlusInterceptor = new MybatisPlusInterceptor();
        // 分页插件
        mybatisPlusInterceptor.addInnerInterceptor(new PaginationInnerInterceptor());
        // 乐观锁插件
        mybatisPlusInterceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        return mybatisPlusInterceptor;
    }

    /**
     * 修改默认的Id生成器，主要是修改设置每个服务的机器序列号，默认是采用的机器Ip取模
     *
     * @return
     */
    @Primary
    @Bean
    public DefaultIdentifierGenerator identifierGenerator() {
        return new DefaultIdentifierGenerator(workerId, datacenterId);
    }

    /**
     * 打印执行sql日志拦截器配置
     * mybatis-plus.global.sql-log配置为true才会加载配置
     *
     * @return
     */
    @Bean
    @ConditionalOnProperty(value = "mybatis-plus.global.sql-log", matchIfMissing = true, havingValue = "true")
    public PrintSqlInterceptor printSqlInterceptor() {
        return new PrintSqlInterceptor();
    }

}
